<?php

namespace DB;

class TranslationService {

    public function readTranslations() {
        $query = "SELECT * FROM `translation`";
        $tr = DAO::getInstance()->query($query, array());

        $result = array();
        foreach ($tr as $r) {
            $result[$r['block']][$r['language_code']][$r['key']] = $r['val'];
        }

        return $result;
    }

    /**
     * @param string $block
     * @param string $key
     * @param string $val
     * @param string $lang
     * @return boolean
     */
    public function addTranslation($block, $key, $val, $lang = 'en') {
        $query = "INSERT INTO `translation` (`key`, `block`, `language_code`, `val`) VALUES (:key, :block, :lang, :val)
			ON DUPLICATE KEY UPDATE `val` = :val";

        $bind = array(
            'key' => $key,
            'block' => $block,
            'lang' => $lang,
            'val' => $val
        );
        DAO::getInstance()->exec($query, $bind);
        return true;
    }

    /**
     * @return array:
     */
    public function getList() {
        $sql = 'SELECT
				l.`code`, l.`name`, k.`block`, k.`key`, t2.`val`
			FROM `language` l
				CROSS JOIN (SELECT DISTINCT `block`, `key` from `translation` t1) k
				LEFT JOIN `translation` t2 on l.`code` = t2.`language_code` AND k.`block` = t2.`block` AND k.`key` = t2.`key`';

        $list = DAO::getInstance()->query($sql);
        return $list;
    }

    public function deleteTranslation($key, $block) {
        $query = "DELETE FROM `translation` where `block` = :block AND `key` = :key";

        $bind = array(
            'key' => $key,
            'block' => $block
        );
        DAO::getInstance()->exec($query, $bind);
        return true;
    }
}
